package kuba.daos;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.logging.Level;

import kuba.bean.Author;
import kuba.bean.CD;
import kuba.common.BeanLogger;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.StaxDriver;

public class CdXmlDAO implements CdDAO{
    private static int counter =1;
    String fileName ="cds.xml";
    private List<CD> cds = new ArrayList<CD>();


    public CdXmlDAO () {
        deserialize();
        int max=0;
        for (CD cd:cds) {
            if (cd.getId() >=max) {
                max = cd.getId();
            }
        }
        counter = max;

    }

    @SuppressWarnings("unchecked")
    private void deserialize(){

        try{
            FileReader fileReader = new FileReader(fileName);
            cds.clear();
            XStream xstream = new XStream(new StaxDriver());
            xstream.alias("CD", CD.class);
            cds = (ArrayList<CD>)xstream.fromXML(fileReader);    
        }catch(Exception e){
            serialize();
            BeanLogger.getLOGGER().log(Level.WARNING,e.toString());
        }
    }

    private void serialize ( ) {
        XStream xstream = new XStream(new StaxDriver());
        FileWriter fileWriter;

        try {
            fileWriter = new FileWriter(fileName);
            xstream.alias("CD", CD.class);
            xstream.toXML(cds, fileWriter);

        } catch (IOException e) {
            BeanLogger.getLOGGER().log(Level.WARNING,e.toString());
        }

    }

    public CD getById(int id) {
        deserialize();
        for (CD cd :cds) {
            if (cd.getId() == id) {
                return cd;
            }
        }
        return null;
    }

    @Override
    public Collection<CD> getAll() {
        deserialize();
        return cds;
    }

    @Override
    public Collection<CD> getByAuthor(Author author) {
        List <CD> authorCds = new ArrayList<CD>();
        deserialize();
        for (CD cd:cds) {
            if (cd.getAuthorId() == author.getId()) {
                authorCds.add(cd);
            }
        }
        return authorCds;
    }

    @Override
    public void insert(CD cd, Author author) {
        deserialize();
        cd.setId(++counter);
        cd.setAuthorId(author.getId());
        cds.add(cd);
        serialize();

    }

    @Override
    public void update(CD cd, Author author) {
        CD cd2 = getById(cd.getId());
        if (cd2 != null) {
            cd.setAuthorId(author.getId());
            cds.remove(cd2);
            cds.add(cd);
            serialize();
        }
    }

    @Override
    public void delete(CD cd) {
        deserialize();
        cds.remove(cd);
        serialize();

    }

}
